package com.cya.forumproject.controller;

import com.cya.forumproject.common.AppResult;
import com.cya.forumproject.common.ResultCode;
import com.cya.forumproject.config.AppConfig;
import com.cya.forumproject.model.User;
import com.cya.forumproject.services.IUserService;
import com.cya.forumproject.utils.MD5Util;
import com.cya.forumproject.utils.StringUtil;
import com.cya.forumproject.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/9/20 11:55
 * @description：
 * @modified By：
 * @version:
 */
@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

//    用户注册
    @ApiOperation(("用户注册"))
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名")@RequestParam("username")@NonNull String username,
                              @ApiParam("昵称")@RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码")@RequestParam("password") @NonNull   String password,
                              @ApiParam("确认密码")@RequestParam("passwordRepeat") @NonNull String passwordRepeat ){
if (StringUtil.isEmpty(username)||StringUtil.isEmpty(nickname)
||StringUtil.isEmpty(password)||StringUtil.isEmpty(passwordRepeat)){
    //返回错误信息
    return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
}
//校验密码与重复密码是否相等
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回异常
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        User user=new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //生成盐
        String salt= UUIDUtil.UUID_32();
//        设置盐和密码
        String encryptPassword = MD5Util.md5Salt(password, salt);

        user.setPassword(encryptPassword);
        user.setSalt(salt);
        //调用service层方法
        userService.createNormalUser(user);
        //返回成功
        return AppResult.success();
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username")@NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password){
        //1. 调用service的登录方法，返回user对象
        User user = userService.login(username, password);
        if (user==null){
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //2. 如果登陆成功将user对象设置到session作用域中
        HttpSession session=request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){

        User user=null;
        //根据id的值来判断user对象的获取方法
        if (id==null){
//            没有session不创建
            HttpSession session=request.getSession(false);

          user= (User) session.getAttribute(AppConfig.USER_SESSION);
        }
        else {
            user=userService.selectById(id);
        }
        if (user==null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

//    用户退出
    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){

//        获取session对象
        HttpSession session=request.getSession(false);
        //判断session是否生效
        if (session!=null){
            log.info("退出成功");
//            销毁session
            session.invalidate();
        }

        return AppResult.success("成功退出");
    }

    /**
     * 修改个人信息
     * @param username
     * @param nickname
     * @param gender
     * @param email
     * @param phoneNum
     * @param remark
     * @return
     */
    @ApiOperation("修改用户信息")
@PostMapping("/modifyInfo")
    public  AppResult modifyInfo(@ApiParam("用户名")@RequestParam(value = "username",required = false) String username,
                                 @ApiParam("昵称")@RequestParam(value = "nickname",required = false)String nickname,
                                 @ApiParam("性别")@RequestParam(value = "gender",required = false)Byte gender,
                                 @ApiParam("邮箱")@RequestParam(value = "email",required = false)String email,
                                 @ApiParam("电话")@RequestParam(value = "phoneNum",required = false)String phoneNum,
                                 @ApiParam("个人简介")@RequestParam(value = "remark",required = false)String remark,
                                 HttpServletRequest request){
        if (StringUtil.isEmpty(username)&&StringUtil.isEmpty(nickname)&&StringUtil.isEmpty(email)
        &&StringUtil.isEmpty(phoneNum)&&StringUtil.isEmpty(remark)&&gender==null){
            //返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }
        User updateUser=new User();
        HttpSession session=request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
//        赋值
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setRemark(remark);
        updateUser.setGender(gender);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setEmail(email);
        userService.modifyInfo(updateUser);
        //查询用户中最新的信息
         user = userService.selectById(user.getId());
//         将最新的用户信息设置到session
         session.setAttribute(AppConfig.USER_SESSION,user);

        return AppResult.success(user);
    }

    @ApiOperation("修改用户密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(@ApiParam("原密码") @RequestParam("oldPassword")@NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword")@NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat")@NonNull String passwordRepeat,
                                    HttpServletRequest request){

//         校验新密码与确认密码是否相等
        if (!newPassword.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        if(session!=null){
            session.invalidate();//销毁sessio，强制登录
        }

//        返回结果
        return AppResult.success();
    }
}